package org.jeecg.modules.flower.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.flower.entity.*;
import org.jeecg.modules.flower.service.IFlowerPlantingBaseService;
import org.jeecg.modules.flower.service.IFlowerPlantingGreenhouseService;
import org.jeecg.modules.flower.service.IFlowerTagInfoService;
import org.jeecg.modules.flower.service.IFlowerTagPrintService;
import org.jeecg.modules.flower.vo.CountNumData;
import org.jeecg.modules.flower.vo.ScreenData;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 标签信息
 * @Author: jeecg-boot
 * @Date:   2021-08-26
 * @Version: V1.0
 */
@Api(tags="标签信息")
@RestController
@RequestMapping("/flower/tagInfo")
@Slf4j
public class FlowerTagInfoController extends JeecgController<FlowerTagInfo, IFlowerTagInfoService> {
	@Autowired
	private IFlowerTagInfoService flowerTagInfoService;
	@Autowired
	private IFlowerTagPrintService tagPrintService;
	 @Autowired
	 private IFlowerPlantingBaseService plantingBaseService;
	 @Autowired
	 private IFlowerPlantingGreenhouseService greenhouseService;
	/**
	 * 分页列表查询
	 *
	 * @param flowerTagInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "标签信息-分页列表查询")
	@ApiOperation(value="标签信息-分页列表查询", notes="标签信息-分页列表查询")
	@GetMapping(value = "/list")
	@PermissionData(pageComponent="flower/FlowerTagInfoList")
	public Result<?> queryPageList(FlowerTagInfo flowerTagInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   @RequestParam(value = "sDate", defaultValue = "") String sDate,
								   @RequestParam(value = "eDate", defaultValue = "") String eDate,
								   HttpServletRequest req) {
//		QueryWrapper<FlowerTagInfo> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagInfo, req.getParameterMap());
		Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(pageNo, pageSize);

		QueryWrapper<FlowerTagInfo> queryWrapper = new QueryWrapper<>();
		if(StringUtils.isNotBlank( flowerTagInfo.getFlowerPoleLength() )){
			queryWrapper.eq("flower_pole_length",flowerTagInfo.getFlowerPoleLength() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getSourceBase() )){
			queryWrapper.eq("source_base",flowerTagInfo.getSourceBase() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getVariety() )){
			queryWrapper.eq("variety",flowerTagInfo.getVariety() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getVarietyCode() )){
			queryWrapper.eq("variety_code",flowerTagInfo.getVarietyCode() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getCost() )){
			queryWrapper.eq("cost",flowerTagInfo.getCost() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getStorehouse() )){
			queryWrapper.eq("storehouse",flowerTagInfo.getStorehouse() );
		}

//		qw.apply(“DATE(createtime) >= STR_TO_DATE(’”+rqq+" 00:00:00’,’%Y-%m-%d %H:%i:%s’)");
//		qw.apply(“DATE(createtime) <= STR_TO_DATE(’”+rqz+" 23:59:59’,’%Y-%m-%d %H:%i:%s’)");

		if (StringUtils.isNotBlank(sDate)) {
			queryWrapper.apply(" date_format( sort_time, '%y-%m-%d') >=  STR_TO_DATE('"+sDate+"','%Y-%c-%d')  " );
//			queryWrapper.ge(FlowerTagInfo::getSortTime , sDate);
		}
		if (StringUtils.isNotBlank(eDate)) {
			queryWrapper.apply(" date_format( sort_time, '%y-%m-%d') <=  STR_TO_DATE('"+eDate+"','%Y-%c-%d')  " );
//			queryWrapper.le(FlowerTagInfo::getSortTime, eDate + " 23:59:59");
		}
		QueryGenerator.installAuthMplus(queryWrapper, FlowerTagInfo.class);

		IPage<FlowerTagInfo> pageList =flowerTagInfoService.queryListAndBase(page, queryWrapper);
//		IPage<FlowerTagInfo> pageList = flowerTagInfoService.page(page, queryWrapper);

//		List<FlowerTagInfo> records = pageList.getRecords();
//		for (FlowerTagInfo record : records) {
//			FlowerPlantingBase base = flowerPlantingBaseService.getById(record.getSourceBase());
//			if (base != null) {
//				record.setBaseName(base.getName());
//			}
//			FlowerPlantingGreenhouse greenhouse = flowerPlantingGreenhouseService.getById(record.getSourceGreenhouse());
//			if (greenhouse != null) {
//				record.setGreenhouseName(greenhouse.getName());
//			}
//		}
		return Result.ok(pageList);
	}

	/**
	 * 分页列表查询
	 *
	 * @param flowerTagInfo
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "-库存台账-t-分页列表查询")
	@ApiOperation(value="-库存台账--分页列表查询", notes="-库存台账--分页列表查询")
	@GetMapping(value = "/getListByhose")
	@PermissionData(pageComponent="flower/FlowerTagInfoList")
	public Result<?> getListByhose(FlowerTagInfo flowerTagInfo,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   @RequestParam(value = "sDate",defaultValue = "") String sDate ,
								   @RequestParam(value = "eDate",defaultValue = "") String eDate,
								   HttpServletRequest req) {
//		QueryWrapper<FlowerTagInfo> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagInfo, req.getParameterMap());
		Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(pageNo, pageSize);

//		LambdaQueryWrapper<FlowerTagInfo> queryWrapper = new LambdaQueryWrapper<>();
		QueryWrapper<FlowerTagInfo> queryWrapper = new QueryWrapper<>();
		if(StringUtils.isNotBlank( flowerTagInfo.getFlowerPoleLength() )){
			queryWrapper.eq("flower_pole_length",flowerTagInfo.getFlowerPoleLength() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getSourceBase() )){
			queryWrapper.eq("source_base",flowerTagInfo.getSourceBase() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getVariety() )){
			queryWrapper.eq("variety",flowerTagInfo.getVariety() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getVarietyCode() )){
			queryWrapper.eq("variety_code",flowerTagInfo.getVarietyCode() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getCost() )){
			queryWrapper.eq("cost",flowerTagInfo.getCost() );
		}
		if(StringUtils.isNotBlank( flowerTagInfo.getStorehouse() )){
			queryWrapper.eq("storehouse",flowerTagInfo.getStorehouse() );
		}

		if (StringUtils.isNotBlank(sDate)) {
			queryWrapper.apply(" date_format( sort_time, '%y-%m-%d') >=  STR_TO_DATE('"+sDate+"','%Y-%c-%d')  " );
//			queryWrapper.ge(FlowerTagInfo::getSortTime , sDate);
		}
		if (StringUtils.isNotBlank(eDate)) {
			queryWrapper.apply(" date_format( sort_time, '%y-%m-%d') <=  STR_TO_DATE('"+eDate+"','%Y-%c-%d')  " );
//			queryWrapper.le(FlowerTagInfo::getSortTime, eDate + " 23:59:59");
		}

		QueryGenerator.installAuthMplus(queryWrapper, FlowerTagInfo.class);

		IPage<FlowerTagInfo> pageList =flowerTagInfoService.getListByhose(page, queryWrapper);
		Integer taginfoCount = flowerTagInfoService.getTaginfoCount(queryWrapper);
		List<FlowerTagInfo> records = pageList.getRecords();
		if(records.size()>0) {
			records.get(0).setSorter(String.valueOf(taginfoCount));
		}
		return Result.ok(pageList);
	}


	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "标签信息-通过id查询")
	@ApiOperation(value="标签信息-通过id查询", notes="标签信息-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		FlowerTagInfo flowerTagInfo = flowerTagInfoService.getById(id);
		if(flowerTagInfo==null) {
			return Result.error("未找到对应数据");
		}
		return Result.ok(flowerTagInfo);
	}
	 /**
	  * 扫码枪接口
	  * 通过id更新标签状态
	  *
	  * @param id
	  * @return
	  */
	 /**
	  * 产品扫一扫
	  * 通过id查询标签信息，并记录扫码次数
	  * @param id
	  * @return
	  */
//	 @AutoLog(value = "标签信息-产品扫一扫")
//	 @ApiOperation(value="标签信息-产品扫一扫", notes="标签信息-产品扫一扫")
	 @GetMapping(value = "/queryAndCountById")
	 public Result<?> queryAndCountById(@RequestParam(name="id",required=true) String id) {
		 FlowerTagPrint flowerTagPrint = tagPrintService.getById(id);
		 if (flowerTagPrint == null) {
			 return Result.error("未找到对应数据");
		 } else {
			 Integer scanTimes = flowerTagPrint.getScanTimes();
			 if (scanTimes != null) {
				 scanTimes = ++scanTimes;
			 } else {
				 scanTimes = 1;
			 }
			 flowerTagPrint.setScanTimes(scanTimes);
			 tagPrintService.updateById(flowerTagPrint);

			 String sourceBase = flowerTagPrint.getSourceBase();
			 String sourceGreenhouse = flowerTagPrint.getSourceGreenhouse();
			 String base ="";
			 FlowerPlantingBase flowerBase = plantingBaseService.getById(sourceBase);
			 String basename = flowerBase.getName();
			 FlowerPlantingGreenhouse lantingGreenhouse = greenhouseService.getById(sourceGreenhouse);
			  base = basename +"-"+lantingGreenhouse.getName();
			 flowerTagPrint.setSourceBase(base);
		 }
		 return Result.ok(flowerTagPrint);
	 }
    /**
    * 导出excel
    *
    * @param request
    * @param flowerTagInfo
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, FlowerTagInfo flowerTagInfo) {
        return super.exportXls(request, flowerTagInfo, FlowerTagInfo.class, "标签信息");
    }


//    /**
//      * 通过excel导入数据
//    *
//    * @param request
//    * @param response
//    * @return
//    */
//    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
//    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return super.importExcel(request, response, FlowerTagInfo.class);
//    }

    //-------------------数据大屏统计--------------------------

	@ApiOperation(value="数据大屏-分拣实况", notes="数据大屏-分拣实况表格")
	@GetMapping(value = "/tableList")
	public Result<?> queryTableList(FlowerTagInfo flowerTagInfo,
									@RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="8") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ScreenData> queryWrapper = new QueryWrapper<>();
		Page<ScreenData> page = new Page<>(pageNo, pageSize);
		IPage<ScreenData> pageList = flowerTagInfoService.selectTablePage(page, queryWrapper);
		return Result.ok(pageList);
	}

	 @ApiOperation(value="数据大屏-花杆长度对比", notes="数据大屏-花杆长度对比")
	 @GetMapping(value = "/poleLengthCom")
	 public Result<?> poleLengthCom() {
		 List<ScreenData> screenData = null;
		 try {
			 screenData = flowerTagInfoService.poleLengthCom();
			 return Result.ok(screenData);
		 } catch (Exception e) {
			 e.printStackTrace();
			 return Result.error(e.getMessage());
		 }
	 }

	 @ApiOperation(value="数据大屏-月度工作量对比", notes="数据大屏-月度工作量对比")
	 @GetMapping(value = "/monthWorkCom")
	 public Result<?> monthWorkCom() {
		 List<ScreenData> screenData = null;
		 try {
			 screenData = flowerTagInfoService.monthWorkCom();
			 return Result.ok(screenData);
		 } catch (Exception e) {
			 e.printStackTrace();
			 return Result.error(e.getMessage());
		 }
	 }

	 @ApiOperation(value="数据大屏-今天、昨天、前天鲜切花", notes="数据大屏-今天、昨天、前天鲜切花")
	 @GetMapping(value = "/currentSortFlower")
	 public Result<?> currentSortFlower() {
		 CountNumData countNumData = null;
		 try {
			 countNumData = flowerTagInfoService.currentSortFlower();
			 return Result.ok(countNumData);
		 } catch (Exception e) {
			 e.printStackTrace();
			 return Result.error(e.getMessage());
		 }
	 }

	 @ApiOperation(value="数据大屏-蔬菜等级-饼图年度", notes="数据大屏-蔬菜等级-饼图年度")
	 @GetMapping(value = "/queryPoleLevelYear")
	 public Result<?> queryPoleLevelYear() {
		 LinkedHashMap<String,Object> result = null;
		 try {
			 result = flowerTagInfoService.queryPoleLevelYear();
			 return Result.ok(result);
		 } catch (Exception e) {
			 e.printStackTrace();
			 return Result.error(e.getMessage());
		 }
	 }

	 @ApiOperation(value="数据大屏-蔬菜等级-饼图月度", notes="数据大屏-蔬菜等级-饼图月度")
	 @GetMapping(value = "/queryPoleLevelMonth")
	 public Result<?> queryPoleLevelMonth() {
		 LinkedHashMap<String,Object> result = null;
		 try {
			 result = flowerTagInfoService.queryPoleLevelMonth();
			 return Result.ok(result);
		 } catch (Exception e) {
			 e.printStackTrace();
			 return Result.error(e.getMessage());
		 }
	 }

	 @ApiOperation(value="数据大屏-品种分布", notes="数据大屏-品种分布")
	 @GetMapping(value = "/queryVariety")
	 public Result<?> queryVariety() {
		 List<LinkedHashMap<String,Object>> result = null;
		 try {
			 result = flowerTagInfoService.queryVariety();
			 return Result.ok(result);
		 } catch (Exception e) {
			 e.printStackTrace();
			 return Result.error(e.getMessage());
		 }
	 }



	 @RequestMapping(value = "/exportXls2")
	 @PermissionData(pageComponent="flower/FlowerTagInfoList")
	 public ModelAndView exportXls2(HttpServletRequest request, FlowerTagInfo flowerTagInfo,
								   @RequestParam(value = "sDate", defaultValue = "") String sDate,
									@RequestParam(value = "eDate", defaultValue = "") String eDate) {
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

		 // Step.2 获取导出数据
//		 List<T> pageList = service.list(queryWrapper);

		 Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(1, 999999999);
		 QueryWrapper<FlowerTagInfo> queryWrapper = new QueryWrapper<>();
		 if(StringUtils.isNotBlank( flowerTagInfo.getFlowerPoleLength() )){
			 queryWrapper.eq("flower_pole_length",flowerTagInfo.getFlowerPoleLength() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getSourceBase() )){
			 queryWrapper.eq("source_base",flowerTagInfo.getSourceBase() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getVariety() )){
			 queryWrapper.eq("variety",flowerTagInfo.getVariety() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getVarietyCode() )){
			 queryWrapper.eq("variety_code",flowerTagInfo.getVarietyCode() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getCost() )){
			 queryWrapper.eq("cost",flowerTagInfo.getCost() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getStorehouse() )){
			 queryWrapper.eq("storehouse",flowerTagInfo.getStorehouse() );
		 }

		 if (StringUtils.isNotBlank(sDate)) {
			 queryWrapper.apply(" date_format( sort_time, '%y-%m-%d') >=  STR_TO_DATE('"+sDate+"','%Y-%c-%d')  " );
//			queryWrapper.ge(FlowerTagInfo::getSortTime , sDate);
		 }
		 if (StringUtils.isNotBlank(eDate)) {
			 queryWrapper.apply(" date_format( sort_time, '%y-%m-%d') <=  STR_TO_DATE('"+eDate+"','%Y-%c-%d')  " );
//			queryWrapper.le(FlowerTagInfo::getSortTime, eDate + " 23:59:59");
		 }
		 QueryGenerator.installAuthMplus(queryWrapper, FlowerTagInfo.class);
		 IPage<FlowerTagInfo> pageList =flowerTagInfoService.getListByhose(page, queryWrapper);

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 String title =  "库存台账";
		 mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, FlowerTagInfo.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList.getRecords());
		 return mv;
	 }

/*	 protected ModelAndView exportXls22(HttpServletRequest request, FlowerTagInfo flowerTagInfo,  String title,String sDate,String eDate) {
		 // Step.1 组装查询条件
//		 QueryWrapper<T> queryWrapper = QueryGenerator.initQueryWrapper(flowerTagInfo, request.getParameterMap());
//		 LoginUser sysUser = JwtUtil.getLoginUser();
		 LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

		 // Step.2 获取导出数据
//		 List<T> pageList = service.list(queryWrapper);

		 Page<FlowerTagInfo> page = new Page<FlowerTagInfo>(1, 999999999);
		 LambdaQueryWrapper<FlowerTagInfo> queryWrapper = new LambdaQueryWrapper<>();
		 if(StringUtils.isNotBlank( flowerTagInfo.getFlowerPoleLength() )){
			 queryWrapper.eq(FlowerTagInfo::getFlowerPoleLength,flowerTagInfo.getFlowerPoleLength() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getSourceBase() )){
			 queryWrapper.eq(FlowerTagInfo::getSourceBase,flowerTagInfo.getSourceBase() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getVariety() )){
			 queryWrapper.eq(FlowerTagInfo::getVariety,flowerTagInfo.getVariety() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getVarietyCode() )){
			 queryWrapper.eq(FlowerTagInfo::getVarietyCode,flowerTagInfo.getVarietyCode() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getCost() )){
			 queryWrapper.eq(FlowerTagInfo::getCost,flowerTagInfo.getCost() );
		 }
		 if(StringUtils.isNotBlank( flowerTagInfo.getStorehouse() )){
			 queryWrapper.eq(FlowerTagInfo::getStorehouse,flowerTagInfo.getStorehouse() );
		 }

		 if (StringUtils.isNotBlank(sDate)) {
			 queryWrapper.apply(" date_format( sort_time, '%y-%m-%d') >=  STR_TO_DATE('"+sDate+"','%Y-%c-%d')  " );
		 }
		 if (StringUtils.isNotBlank(eDate)) {
			 queryWrapper.apply(" date_format( sort_time, '%y-%m-%d') <=  STR_TO_DATE('"+eDate+"','%Y-%c-%d')  " );
		 }

		 IPage<FlowerTagInfo> pageList =flowerTagInfoService.getListByhose(page, queryWrapper);

		 // Step.3 AutoPoi 导出Excel
		 ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		 mv.addObject(NormalExcelConstants.FILE_NAME, title); //此处设置的filename无效 ,前端会重更新设置一下
		 mv.addObject(NormalExcelConstants.CLASS, FlowerTagInfo.class);
		 mv.addObject(NormalExcelConstants.PARAMS, new ExportParams(title + "报表", "导出人:" + sysUser.getRealname(), title));
		 mv.addObject(NormalExcelConstants.DATA_LIST, pageList.getRecords());
		 return mv;
	 }*/
}
